package com.taofengsdk.widegt;

import android.app.Dialog;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.taofengsdk.R;
import com.taofengsdk.adutil.Utils;
import com.taofengsdk.constant.SDKConstant;
import com.taofengsdk.model.AdValue;
import com.taofengsdk.video.core.VideoAdSlot;
import com.taofengsdk.video.report.ReportManager;

/**
 * Created by tao on 17-3-16.
 */

public class VideoFullDialog extends Dialog implements CustomVideoView.ADVideoPlayerListener {
    private static final String TAG = VideoFullDialog.class.getName();
    private Context mContext;
    /**
     * UI
     */
    private CustomVideoView mVideoView;
    private ViewGroup mParentView;
    private ImageView mBackBtn;
    private RelativeLayout mRootView;
    /**
     * Data
     */
    private AdValue mXAdInstance;
    private FullToSmallListener mToSmallListener;
    private int mPosition; //从小屏到全屏是的播放位置
    private boolean mIsFirst = true;

    //动画要执行的平移值
    private int deltaY;
    private VideoAdSlot.AdSDKSlotListener mSlotListener;
    private Bundle mStartBundle;
    private Bundle mEndBundle; //用于Dialog出入场动画

    public VideoFullDialog(@NonNull Context context, CustomVideoView videoView,
                           AdValue value, int position) {
        super(context, R.style.dialog_full_screen);
        this.mContext = context;
        this.mVideoView = videoView;
        this.mXAdInstance = value;
        this.mPosition = position;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.xadsdk_dialog_video_layout);

        initVideoView();
    }

    private void initVideoView() {
        mParentView = (ViewGroup) findViewById(R.id.content_layout);
        mBackBtn = (ImageView) findViewById(R.id.xadsdk_player_close_btn);
        mRootView = (RelativeLayout) findViewById(R.id.root_view);
        mBackBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickBackBtn();
            }
        });
        mVideoView.setAdvideoPlayListener(this);
        mVideoView.setIsMute(false);
        mParentView.addView(mVideoView);
        mParentView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                mParentView.getViewTreeObserver().removeOnPreDrawListener(this);
                prepareScene();
                runEnterAnimation();
                return true;
            }
        });
    }

    //准备动画所需数据
    private void prepareScene() {
        mEndBundle = Utils.getViewProperty(mVideoView);
        /**
         * 将desationview移到originalview位置处
         */
        deltaY = (mStartBundle.getInt(Utils.PROPNAME_SCREENLOCATION_TOP)
                - mEndBundle.getInt(Utils.PROPNAME_SCREENLOCATION_TOP));
        mVideoView.setTranslationY(deltaY);
    }

    //准备入场动画
    private void runEnterAnimation() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mVideoView.animate()
                    .setDuration(200)
                    .setInterpolator(new LinearInterpolator())
                    .translationY(0)
                    .withStartAction(new Runnable() {
                        @Override
                        public void run() {
                            mRootView.setVisibility(View.VISIBLE);
                        }
                    })
                    .start();
        }
    }

    //准备出场动画
    private void runExitAnimator() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mVideoView.animate()
                    .setDuration(200)
                    .setInterpolator(new LinearInterpolator())
                    .translationY(deltaY)
                    .withEndAction(new Runnable() {
                        @Override
                        public void run() {
                            dismiss();
                            try {
                                ReportManager.exitfullScreenReport(mXAdInstance.event.exitFull.content, mVideoView.getCurrentPosition()
                                        / SDKConstant.MILLION_UNIT);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            if (mToSmallListener != null) {
                                mToSmallListener.getCurrentPlayPosition(mVideoView.getCurrentPosition());
                            }
                        }
                    }).start();
        }
    }

    public void setViewBundle(Bundle bundle) {
        mStartBundle = bundle;
    }

    public void setSlotListener(VideoAdSlot.AdSDKSlotListener slotListener) {
        this.mSlotListener = slotListener;
    }

    @Override
    public void onBufferUpdate(int time) {

    }

    @Override
    public void onClickFullScreenBtn() {
        onClickBackBtn();
    }

    @Override
    public void onClickVideo() {
//        String desationUrl = mXAdInstance.clickUrl;
//        if (!TextUtils.isEmpty(desationUrl)) {
//            Intent intent = new Intent(mContext, AdBrowserActivity.class);
//            intent.putExtra(AdBrowserActivity.KEY_URL, mXAdInstance.clickUrl);
//            mContext.startActivity(intent);
//        }
    }

    @Override
    public void onClickBackBtn() {
        dismiss();
        if (mToSmallListener != null) {
            mToSmallListener.getCurrentPlayPosition(getPosition());
        }
    }

    @Override
    public void onClickPlay() {
        if (isPlaying()) {

        } else {
            mVideoView.resume();
        }
    }

    @Override
    public void onAdVideoLoadSuccess() {
        if (mVideoView != null) {
            mVideoView.resume();
        }
    }

    @Override
    public void onAdVideoLoadFailed() {

    }

    @Override
    public void onAdVideoLoadComplete() {
        try {
            int position = mVideoView.getDuration() / SDKConstant.MILLION_UNIT;
            ReportManager.sueReport(mXAdInstance.endMonitor, true, position);
        } catch (Exception e) {
            e.printStackTrace();
        }

        dismiss();
        if (mToSmallListener != null) {
            mToSmallListener.onVideoPlayComplete();
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        onClickBackBtn();
    }

    /**
     * 焦点改变时的回调
     *
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (!hasFocus) {
            mPosition = getPosition();
            mVideoView.pause();
        } else {
            if (isFirst()) {
                if (isPlaying()) {
                    mVideoView.seekAndResume(mPosition);
                } else {
                    mVideoView.seekAndPause(mPosition);
                }
            } else {
                if (isPlaying()) {
                    mVideoView.resume();
                } else {
                    mVideoView.pause();
                }
            }
        }
        setIsFirst(false);
    }

    @Override
    public void dismiss() {
        super.dismiss();
        mParentView.removeView(mVideoView);
    }

    private int getPosition() {
        mPosition = mVideoView.getCurrentPosition();
        return mPosition;
    }

    private boolean isPlaying() {
        return mVideoView.isPlaying();
    }

    private boolean isRealPause() {
        return mVideoView.isRealPause();
    }

    private boolean isComplete() {
        return mVideoView.isComplete();
    }

    private boolean isFirst() {
        return mIsFirst;
    }

    private void setIsFirst(boolean isFirst) {
        this.mIsFirst = isFirst;
    }


    public void setFullToSmallListener(FullToSmallListener toSmallListener) {
        mToSmallListener = toSmallListener;
    }

    /**
     * 与业务逻辑层(VideoAdslot)通信
     */
    public interface FullToSmallListener {
        void getCurrentPlayPosition(int position); //全屏时视屏播放的位置,当返回小屏时调用

        void onVideoPlayComplete();  //全屏时视频播放完成时调用
    }
}
